import React, { ReactNode } from 'react';
import { View, Text, Image } from '@tarojs/components';
import Taro from '@tarojs/taro';
import './index.less';
import store from '@/src/store';
import { AtNoticebar } from 'taro-ui';
import { userInfoFun } from '@/src/common/method/loginFun';

interface TitleBarProps {
  title?: string; // 标题文字
  customCenter?: ReactNode; // 中间自定义节点
  showLeftBack?: boolean; // 是否显示默认返回按钮
  customLeft?: ReactNode; // 左侧自定义节点，优先级高于 showLeftBack
  customRight?: ReactNode; // 右侧自定义节点
  onBack?: () => void; // 返回点击回调
  theme?: 'light' | 'dark'; // 主题：light | dark
}

const TitleBar: React.FC<TitleBarProps> = ({
  title,
  customCenter,
  showLeftBack = false,
  customLeft,
  customRight,
  onBack,
  theme = 'light',
}) => {
  const handleBack = () => {
    //1.判断用户是否登录

    //1.传返回方法则直接调用；2.用户没有登录则跳转到登录；3.直接返回上一页
    if (onBack) {
      onBack();
    }
    // else if (
    //   Taro.getStorageSync('access_token_login') === '' ||
    //   Taro.getStorageSync('userId') === ''
    // ) {
    //   Taro.reLaunch({ url: '/subPagesAuth/login/index' });
    // }
    else {
      Taro.navigateBack()
        .then((res: any) => {
          console.log(res, '返回成功啦');
        })
        .catch((e: any) => {
          console.log(e, '返回失败');
          Taro.switchTab({ url: '/pages/home/index' });
        });
    }
  };

  // 根据主题选择返回按钮图标
  const backIcon =
    theme === 'dark'
      ? 'https://file.linkcook.cn/image/wineMiniProgram/imgs/scan/back-white.png'
      : 'https://file.linkcook.cn/image/wineMiniProgram/back.png';

  const renderLeft = () => {
    if (customLeft) return customLeft;
    if (showLeftBack) {
      return <Image className="tb-back" src={backIcon} onClick={handleBack} />;
    }
    return null;
  };

  const renderCenter = () => {
    if (customCenter) return customCenter;
    if (title)
      return (
        <Text className={`tb-title tb-title-${theme} clamp1`}>{title}</Text>
      );
    return null;
  };

  return (
    <View
      className={`title-bar title-bar-${theme}`}
      style={{ paddingTop: `${store.commonStore.safeAreaTop}rpx` }}
    >
      <View className="tb-left">{renderLeft()}</View>
      <View className="tb-center">{renderCenter()}</View>
      <View className="tb-right">{customRight}</View>
    </View>
  );
};

export default TitleBar;
